import { useCallback, useEffect, useRef } from 'react';
import {
    FlameChartNodes,
    FlameChartSettings,
    Marks,
    Waterfall,
    FlameChart,
    WaterfallItem,
    Mark,
    UIPlugin,
    FlatTreeNode,
    Timeseries,
} from '../../index';
import useResizeObserver from 'use-resize-observer';

export type NodeTypes =
    | { node: FlatTreeNode | null; type: 'flame-chart-node' }
    | { node: WaterfallItem | null; type: 'waterfall-node' }
    | { node: Mark | null; type: 'mark' }
    | null;

export type FlameChartWrapperProps = {
    data?: FlameChartNodes;
    marks?: Marks;
    waterfall?: Waterfall;
    timeseries?: Timeseries;
    timeframeTimeseries?: Timeseries;
    colors?: Record<string, string>;
    settings?: FlameChartSettings;
    position?: { x: number; y: number };
    zoom?: {
        start: number;
        end: number;
    };
    plugins?: UIPlugin[];
    hotkeys?: boolean;
    instance?: (instance: FlameChart) => void;
    className?: string;

    onSelect?: (data: NodeTypes) => void;
};
// 添加时间格式化辅助函数
const formatTime = (timestamp: number):string=> {
    const date = new Date(timestamp);
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`;
}
export const FlameChartComponent = (props: FlameChartWrapperProps) => {
    const boxRef = useRef<null | HTMLDivElement>(null);
    const canvasRef = useRef<null | HTMLCanvasElement>(null);
    const flameChart = useRef<null | FlameChart>(null);
    // 添加时间格式化函数
    function formatDateTime(timestamp: number) {
        const date = new Date(timestamp);
        const year = date.getFullYear();
        const month = (date.getMonth() + 1).toString().padStart(2, '0');
        const day = date.getDate().toString().padStart(2, '0');
        const hours = date.getHours().toString().padStart(2, '0');
        const minutes = date.getMinutes().toString().padStart(2, '0');
        const seconds = date.getSeconds().toString().padStart(2, '0');
        const milliseconds = date.getMilliseconds().toString().padStart(3, '0');

        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    }
    // 验证是否是时间戳
    function isValidTimestamp(timestamp: number) {
        const date = new Date(timestamp);
        return date.getTime() > 0;  // 有效的时间戳会返回一个大于0的值
    }

    useResizeObserver({
        ref: boxRef,
        onResize: ({ width = 0, height = 0 }) => flameChart.current?.resize(width, height - 3),
    });

    const initialize = useCallback(() => {
        const { data, marks, waterfall, timeseries, settings, colors, plugins, timeframeTimeseries } = props;

        if (canvasRef.current && boxRef.current) {
            const { width = 0, height = 0 } = boxRef.current.getBoundingClientRect();

            canvasRef.current.width = width;
            canvasRef.current.height = height - 3;
            console.log("settings",settings)
            flameChart.current = new FlameChart({
                canvas: canvasRef.current,
                data,
                //marks,
               // waterfall,
                //timeseries,
                //timeframeTimeseries,
                settings,
                colors,
               // plugins,
                customTimeLineToolTipData:(data)=>{
                    return data.map(item=>{
                        const timestamp=item.text.split(" ")[0];
                        if(isValidTimestamp(Number(timestamp))){
                            return {
                                text:formatDateTime(Number(timestamp)),
                            }
                        }else{
                            return {
                                text:item.text,
                            }
                        }
                    })
                },
                setTimeLineGridRender:(pixelPosition, timePosition)=>{
                    const currentTime=formatTime(timePosition)
                    return {currentTime}
                },
                customRenderFlameGrapToolTip:(data)=>{
                    const { start, duration, name } = data;
                    return [
                            { key: "名字", value: name },
                            { key: "耗时", value: `${formatDateTime(duration)}` },
                            { key: "开始时间", value: formatDateTime(start) }
                          ];
                },
                
            });
            flameChart.current.on('click', ({ node, options }) => {
                console.log('节点被点击：', node);
                console.log('使用的样式：', options);
            });
            

            props.instance?.(flameChart.current);
        }
    }, []);

    const setBoxRef = useCallback((ref: HTMLDivElement) => {
        const isNewRef = ref !== boxRef.current;

        boxRef.current = ref;

        if (isNewRef) {
            initialize();
        }
    }, []);

    const setCanvasRef = useCallback((ref: HTMLCanvasElement) => {
        const isNewRef = ref !== canvasRef.current;

        canvasRef.current = ref;

        if (isNewRef) {
            initialize();
        }
    }, []);

    useEffect(() => {
        if (props.data) {
            flameChart.current?.setNodes(props.data);
        }
    }, [props.data]);

    useEffect(() => {
        if (props.marks) {
            flameChart.current?.setMarks(props.marks);
        }
    }, [props.marks]);

    useEffect(() => {
        if (props.waterfall) {
            flameChart.current?.setWaterfall(props.waterfall);
        }
    }, [props.waterfall]);

    useEffect(() => {
        if (props.timeseries) {
            flameChart.current?.setTimeseries(props.timeseries);
        }
    }, [props.timeseries]);

    useEffect(() => {
        if (props.timeframeTimeseries) {
            flameChart.current?.setTimeframeTimeseries(props.timeframeTimeseries);
        }
    }, [props.timeframeTimeseries]);

    useEffect(() => {
        if (props.settings && flameChart.current) {
            console.log("flameChart.current", flameChart.current)
            flameChart.current.setSettings(props.settings);
            flameChart.current.renderEngine.recalcChildrenLayout();
            flameChart.current.render();
        }
    }, [props.settings]);

    useEffect(() => {
        if (props.position) {
            flameChart.current?.setFlameChartPosition(props.position);
        }
    }, [props.position]);

    useEffect(() => {
        if (props.zoom) {
            flameChart.current?.setZoom(props.zoom.start, props.zoom.end);
        }
    }, [props.zoom]);

    useEffect(() => {
        if (typeof props.hotkeys === 'boolean') {
            flameChart.current?.hotkeys(props.hotkeys);
        }
    }, [props.hotkeys]);

    useEffect(() => {
        if (props.onSelect) {
            flameChart.current?.on('select', props.onSelect);
        }

        return () => {
            if (props.onSelect) {
                flameChart.current?.removeListener('select', props.onSelect);
            }
        };
    }, [props.onSelect]);

    return (
        <div className={props.className} ref={setBoxRef}>
            <canvas ref={setCanvasRef} />
        </div>
    );
};
